const jwt = require('jsonwebtoken') //获取token
const { security } = require('../config')
/***
 * 
 */
const findMembers = function (instance, {
    prefix,
    specifiedType,
    filter
}) {
    // 递归函数
    function _find(instance) {
        //基线条件（跳出递归）
        if (instance.__proto__ === null)
            return []

        let names = Reflect.ownKeys(instance)
        names = names.filter((name) => {
            // 过滤掉不满足条件的属性或方法名
            return _shouldKeep(name)
        })

        return [...names, ..._find(instance.__proto__)]
    }

    function _shouldKeep(value) {
        if (filter) {
            if (filter(value)) {
                return true
            }
        }
        if (prefix)
            if (value.startsWith(prefix))
                return true
        if (specifiedType)
            if (instance[value] instanceof specifiedType)
                return true
    }

    return _find(instance)
}

//获取token
/**
 * 
 * @param {id} uid 
 * @param {权限} scope 
 */
const generateToken = function(uid, scope){
    const secretKey = security.secretKey
    const expiresIn = security.expiresIn
    const refreshExpiresIn = security.refreshExpiresIn
    //生成令牌 
    /**
     * 参数1： 自定义信息对象
     * 参数2： secretKey 私有钥匙、开发者定义
     * 参数3： 可选的配置项
     */
    const token = jwt.sign({
        uid
    },secretKey,{
        expiresIn
    })
    const refreshToken = jwt.sign({
        uid,
        scope
    },secretKey,{
        expiresIn:refreshExpiresIn
    })
    return {
        token,
        refreshToken
    }
}
module.exports = {
    findMembers,
    generateToken,
}